﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Checkpoint2XNA.Models
{
    public class CheckerPlane: Model3D
    {
        public Vector3 Normal { get; set; }
        public Vector3 Pos { get; set; }
        public Vector3 Max { get; set;}
        public float F { get; set; }


        public float Width;

        protected Color color;
        protected Color color2;
        public double checkerSize;

        public CheckerPlane(Vector3 lowerLeft, float width, Color c, Color c2)
        {
            Normal = new Vector3(0, 1, 0);
            Pos = lowerLeft;
            F = Vector3.Dot(Normal, lowerLeft);
            Max = new Vector3(Pos.X + width, Pos.Y, Pos.Z + width);
            Width = width;
            color = c;
            color2 = c2;
            checkerSize = width/8.0;
        }

        public override void MoveTo(Vector3 point)
        {
            throw new NotImplementedException();
        }

        public override Color GetColorAt(Vector3 point)
        {
            int row = (int)((point.X - Pos.X) / checkerSize);
            int column = (int)((point.Z - Pos.Z) / checkerSize);

            if (row % 2 == column % 2)
                return color;
            else
                return color2;
        }

        public override Vector3 GetNormal(Vector3 point)
        {
            return Normal;
        }

        public override double RayCollide(Vector3 origin, Vector3 vector)
        {          
            double Vd = Vector3.Dot(Normal, vector);

            if (Vd < 0)
            {
                double V0 = Vector3.Dot(Normal, Max - origin);

                double t = V0 / Vd;
                

                if (t > 0)
                {
                    Vector3 intersection = new Vector3(vector.X * (float)t + origin.X,
                                                       Pos.Y,
                                                       vector.Z * (float)t + origin.Z);

                    if (intersection.X < Pos.X || intersection.X > Max.X ||
                        intersection.Z < Pos.Z || intersection.Z > Max.Z)
                    {
                        return -1;
                    }

                    return t;
                }
            }

            return -1;
        }
        
    }
}
